/*
 * @Author: ✨Fireflx 
 * @Date: 2022-02-14 17:58:29 
 * @Last Modified by: ✨Fireflx
 * @Last Modified time: 2022-02-16 22:52:01
 */


const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require("koa2-cors")
const koajwt = require("koa-jwt")

const MongoDBConnect = require('./db')

const {
  users,
  accounts,
  upload,
  article,
  comments,
  fans,
} = require('./routes')

//链接数据库
MongoDBConnect()

// error handler
onerror(app)

// middlewares
//一定注意中间件的位置
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(cors())
app.use(require('koa-static')(__dirname + '/public'))
//一定要注意静态资源获取在token限制之前
app.use(koajwt({
  secret:'jwt-server-admin'
}).unless({
  //不验证token的借口
  path:[/^\/accounts\/login/,/^\/accounts\/reg/,/^\/accounts\/key/]
}))


app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(users.routes(), users.allowedMethods())
app.use(accounts.routes(), accounts.allowedMethods())
app.use(upload.routes(), upload.allowedMethods())
app.use(article.routes(), article.allowedMethods())
app.use(comments.routes(), comments.allowedMethods())
app.use(fans.routes(), fans.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
